//import Player     from './player/index'
import DataBus    from './databus'

import Player     from './player/player'
import Enemy      from './npc/enemy'
import BackGround from './runtime/background'
import Beans      from './runtime/beans'
import GameInfo   from './runtime/gameinfo'
import Music      from './runtime/music'

let ctx   = canvas.getContext('2d')
let databus = new DataBus()


const NPC_COLOR = ['#F00','#F93','#0CF','#F9C']	//NPC颜色
var beakflagflag=false//玩家被吃后，设置这个中断标志
	
/**
 * 游戏主函数
 */
export default class Main {
  constructor() {
    // 维护当前requestAnimationFrame的id
    this.aniId    = 0

	databus.reset()
	
	this.restart()
	
	
  }

  restart() {
    
    
    databus.resetmapoffset()
    
	this.bg       = new BackGround(ctx)
	
	if (!beakflagflag){
        this.beans    = new Beans(ctx) //进入新的一关，生成新的bean
	    this.bg.setbeans(this.beans)
		
	}else{
		this.bg.setbeans(this.beans)
	}
	
	beakflagflag=false
	
	this.player   = new Player(ctx)
	this.player.setbeans(this.beans)
	
	databus.setplayer(this.player)
	
	this.enemys=new Array(databus.NPC_NUM)
	this.player.setenemys(this.enemys)

	for(var i=0;i<databus.NPC_NUM;i++){
	  this.enemys[i]=new Enemy(i+1,3,NPC_COLOR[i],{x:12+i,y:14},{x:12+i,y:14},2,0.8)
	  this.enemys[i].setPlayer(this.player)
	}
	
	databus.setnpcitems(this.enemys)
    
	
	this.music    = new Music()

    this.bindLoop     = this.loop.bind(this)
    this.hasEventBind = false

    // 清除上一局的动画
    window.cancelAnimationFrame(this.aniId);

    this.aniId = window.requestAnimationFrame(
      this.bindLoop,
      canvas
    )
  }

  
 

  
  /**
   * canvas重绘函数
   * 每一帧重新绘制所有的需要展示的元素
   */
  render() {
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    this.bg.render(ctx)
	this.beans.render(ctx)
	this.player.render(ctx)
	
	
	for(var i=0;i<databus.NPC_NUM;i++){
	   this.enemys[i].render(ctx)
	}

  }  

  // 游戏逻辑更新主函数
  update() {
    
    
    this.bg.update()
	this.player.update()
	this.beans.update()
	
	
	for(var i=0;i<databus.NPC_NUM;i++){
	   this.enemys[i].update()
	}
	
	
  }
	


  // 实现游戏帧循环
  loop() {
	
	if (!databus.gameALLOver && !databus.gamepause ){
    
	  if (databus.gamestart==false && databus.gameOver==true){ //进入下一关
	     this.restart()
	     return
	  }

	  
	  databus.frame++
      this.update()
      this.render()
	  this.music.playBgm()

	  if (this.player.getstatus()==3 && this.player.timeout2==0) {//玩家被吃
	      
	      //this.player.relife();
		  beakflagflag=true; //设置中断标志
	      this.restart()
		  return 
		  
	  }
	  
	  
	}else{
		this.music.pauseBgm()
	}
	//循环主体,必须执行
	this.aniId = window.requestAnimationFrame(
		  this.bindLoop,
		  canvas
	  )
  }
}
